<?php
namespace App\Http\Controllers\Admin\UserCenter;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Repositories\UsersRepository;
use Log;
use Storage;
use Illuminate\Support\Facades\DB;
use App\Repositories\UsersInRolesRepository;
/**
 * 后台的用户相关的接口
 */
class IndexController extends Controller
{

	public function __construct()
	{
		$this->middleware('auth:users', ['except' => ['check']]);
	}
  
 
	/*
	 *  上传自己的头像
	 */
	public function UploadFace(Request $request, UsersRepository $UsersRepository)
	{
		$user = auth('users')->user();
		if ($request->hasFile('file')) {

			$file = $request->file('file');
 
			$ext = $file->getClientOriginalExtension(); 
			$realPath = $file->getRealPath();  
			$type = $file->getClientMimeType();  
 
			$filename = uniqid() . '.' . $ext;
			//Log::info($filename);
			if (in_array(strtolower($file->extension()), ['jpeg', 'jpg', 'gif', 'gpeg', 'png'])) {
				// 使用我们新建的uploads本地存储空间（目录）
				//这里的upload是配置文件的名称
				$bool = Storage::disk('oss')->put("/avatar/users/" . $filename, file_get_contents($realPath));
				//判断是否创建成功
				if (!$bool) {
					return response()->json(['code' => 1, 'message' => '头像上传失败']);
				}
				else {
					if (trim($user->Avatar) != '') {
						//删除旧的头像
						Storage::disk('oss')->delete("/avatar/users/" . $user->Avatar);
					}
					$UsersRepository->update(['Avatar' => $filename], $user->ID);
					return response()->json(['code' => 0, 'message' => '头像上传成功', 'result' => $filename]);
				}
			}
			else {
				return response()->json(['code' => 1, 'message' => '请选择图片文件']);
			}
		}

	}
	 
	/**
	 *  修改自己的密码
	 */
	public function ChangePassword(Request $request, UsersRepository $UsersRepository)
	{
		$user = auth('users')->user();
		$credentials = [
			'password' => trim($request->input('OLDPassword')),
			'accountname' => $user->AccountName
		];
		 
		if ($token = auth('users')->attempt($credentials)) {

			$UsersRepository->update(['Password' => bcrypt(trim($request->input('Password')))], $user->ID);
			return response()->json([
				'code' => 0,
				'access_token' => $token,
				'token_type' => 'bearer',
				'expires_in' => auth('users')->factory()->getTTL() * 60,
				'result' => auth('users')->user(),
				'message' => '密码修改成功'
			]);

		}
		else {
			return response()->json(['code' => 1, 'message' => '旧密码错误']);
		}

	}
 
	 
	public function EditInfo(UsersRepository $UsersRepository, Request $request)
	{
		$requestData = [
			'Name' => trim($request->input('Name')),
			'MobileTelephone' => trim($request->input('MobileTelephone')),
			'Email' => trim($request->input('Email')),
			'QQ' => trim($request->input('QQ')),
			'Wechat' => trim($request->input('Wechat')),
		];
		$user = auth('users')->user();
		$ID = $user->ID;
		$UsersRepository->update($requestData, $ID);
		return response()->json(['code' => 0, 'message' => '完成资料设置']);

	}
	 
}